import {ChangeDetectorRef, Component,  ViewChild} from '@angular/core';
import {Content, IonicPage, NavController, NavParams, Select, ToastController,Loading,Events} from 'ionic-angular';
import {CallNumber} from '@ionic-native/call-number';

import {ClientVipProvider} from '../../../providers/client/client-vip/client-vip.provider';
import {ClientListItemModel} from "../../../model/pages/client/client-list/client-list-item.model";
import {ClientNoteEditProvider} from "../../../providers/client/client-note/client-note-edit/client-note-edit.provider";
import {InfiniteScrollModel} from "../../../model/common/infinite-scroll.model";
import {PageParamsModel} from "../../../model/common/page-params.model";
import {MessageBushService} from "../../../services/common/message-bush.service";
import {SideMenuService} from "../../../services/common/side-menu.service";
import {TabsPage} from "../../tabs/tabs";
import {ClientFilterComponent} from "../../../components/pages/client/client-filter/client-filter.component";
import {ClientFilterWayModel} from "../../../model/pages/client/client-list/client.model";
import {CallNumberService} from "../../../services/native/call-number/call-number.service";
import {LoadingService} from "../../../services/common/loading.service";
import {AdpActionSheetController} from "../../../components/common/adp-action-sheet/adp-action-sheet-controller";

@IonicPage()
@Component({
    selector: 'page-client-vip',
    templateUrl: 'client-vip.html',
    providers: [
        ClientVipProvider,
        CallNumber,
        ClientNoteEditProvider,
        SideMenuService,
        CallNumberService
    ]
})
export class ClientVipPage extends InfiniteScrollModel {
    //正在刷新
    refreshing:boolean = false;
    clientsData: Array<any>;
    infiniteScroll = null;
    searchKeyword: string;
    // 点击进入客户详情
    clickStatus: boolean = true;
    //数据添加方式(0为替换，1为追加)
    addDataWay = 0;
    //搜索关键字
    _searchWord: string;
    set searchWord(value: string) {
        this._searchWord = value;
        this.pageParams.condition.keyword = value;
    }
    get searchWord(): string {
        return this._searchWord;
    }
    dataTotal:string;
    dataTotalCount:number;
    get clientItemHeight():string{
        const windowW = window['innerWidth'];
        return (windowW * 38.34 / 100) + 'px';
    }
    currentClient;
    currentMobileList;
    currentMobile;
    isScrolling = false;
    isViewDidLoad = false;
    isArriveBottom = false;
    isLoaded: boolean = false;
    @ViewChild('selectMobile') selectMobile: Select;
    @ViewChild(Content) content: Content;
    @ViewChild('clientFilterTool') clientFilterTool: ClientFilterComponent;
    clientSortPage = ClientFilterWayModel.ClientVipListPage;
    dataItemSearchWrapper = {
        isSearchWrapper:true
    };

    openRoot=(name, index)=>this.openTab(name, index);

    openMenu(myEvent){
        this.sideMenuService.openSideMenu(myEvent)
    }

    openTab(name, index){
        this.navCtrl.popToRoot();
        this.tabsPage.openPage({name:name, index:index});
    }

    constructor(public navCtrl: NavController,
                public navParams: NavParams,
                public cliVipPro: ClientVipProvider,
                public changeRef:ChangeDetectorRef,
                private callNumber: CallNumber,
                private clientNoteEditProvider: ClientNoteEditProvider,
                public toastCtrl: ToastController,
                private sideMenuService:SideMenuService,
                public tabsPage:TabsPage,
                private callNumberService: CallNumberService,
                public loadService:LoadingService,
                public adpActionSheetController:AdpActionSheetController,
                public events:Events
                ) {
        super();
    }

    ionViewDidLoad(){
        this.isViewDidLoad = true;

        this.getDataTotal().subscribe((res) => {
            this.pageInfo.pageSize = this.dataTotalCount = res && res.total?res.total:0;
            this.getVipListData(1,() => {
                this.loadService.dismissLoading();
            });
        },error2 => {
            this.loadService.dismissLoading()
        });
    }
    ionViewDidEnter() {
        setTimeout(() => {
            this.clickStatus = false;
        }, 4500);
        const flag = MessageBushService.getMessage(MessageBushService.keys.vipClientListUpdated);
        if(flag == "1" && !this.isViewDidLoad){
            this.ionViewDidLoad();
            MessageBushService.setMessage(MessageBushService.keys.vipClientListUpdated,'0');
        }
        this.isViewDidLoad = false;
    }

    scrollStart(e){
        this.isScrolling = true;
    }
    scrollEnd(e){
        this.isScrolling = false;
    }

    scrolling(){
        const dimensions = this.content.getContentDimensions();
        if((!this.clientsData || this.clientsData.length<5) && this.isLoaded){
            return;
        }
        const temp1 = dimensions.scrollHeight - dimensions.scrollTop - dimensions.contentHeight < 100;

        if(temp1 !== this.isArriveBottom){
            this.isArriveBottom = temp1;
            this.changeRef.detectChanges();
        }
    }

    goVipInterests(){
        this.navCtrl.push('ClientVipInterestsPage');
    }

    /**
     * 格式化千分位
     * @param numP
     * @returns {string}
     */
    toThousands(numP) {
        let num = (numP || 0).toString(), result = '';
        while (num.length > 3) {
            result = ',' + num.slice(-3) + result;
            num = num.slice(0, num.length - 3);
        }
        if (num) {
            result = num + result;
        }
        return result;
    }

    goUp() {
        if(this.isScrolling){
            setTimeout(() => {
                this.goUp();
            },300);
            return;
        }
        this.content.scrollToTop();
    }

    /**
     * 获取vip列表数据
     */
    getVipListData(isLoading = 1, cb = null) {
        this.isLoaded = false;
        this.isArriveBottom = false;
        let p = void 0;
        this.pageParams.pageSize = this.dataTotalCount;
        this.cliVipPro.getVipList(isLoading, this.pageParams).subscribe(res => {
            if (this.addDataWay === 0) {
                this.clientsData = res.list;
            } else {
                this.clientsData = this.clientsData.concat(res.list);
            }
            this.pageInfo = res;
            this.isLoaded = true;
            if(!res.list || !res.list.length){
                this.dataTotal = '(0)';
            }else{
                this.dataTotal = `(${this.pageInfo.total})`;
            }
            //过滤为空的电话号码
            this.clientsData = this.cliVipPro.checkMobileNull(this.clientsData);
            if(this.clientsData.indexOf(this.dataItemSearchWrapper)==-1){
                this.clientsData.unshift(this.dataItemSearchWrapper);
            }
            if (cb) cb(p);
            this.isLoaded = true;
        }, (code) => {
            if (cb) cb(p);
            this.isLoaded = true;
        });
    }

    getDataTotal(){

        const param: PageParamsModel = {
            pageNum: 1,
            pageSize: 0,
            orderType: this.pageParams.orderType,
            orderName: null,
            condition: {}
        };
        this.loadService.showLoading();
        this.events.publish('checkNet');
        return  this.cliVipPro.getVipList(0,param)
        //     .subscribe(res=>{
        //     this.loadService.dismissLoading();
        //     return res;
        // },error2 => {
        //     this.loadService.dismissLoading();
        // })
       // this.pageInfo.pageSize = this.dataTotalCount = vipItems && vipItems['total']?vipItems['total']:0;
       //  vipItems['total'];
    }

    /**
     *  toast 提示信息
     * @param {string} message 提示内容
     * @param {string} position 显示位置
     */
    toast(message: string, position: string) {
        this.toastCtrl.create({
            message: message,
            position: 'middle',
            duration: 1200
        }).present();
    }

    //调用原生打电话
    nativeCallPhone(mobilePhone?:string){
        if(mobilePhone) this.currentMobile = mobilePhone;
        this.callNumberService.makeCall(this.currentMobile,
            this.callNumberService.initClientNoteLog(this.currentClient.clientId),
            true,
            this.callNumberService.initFollowStateLog(this.currentClient.clientId));
    }

    /**
     * 打电话
     */
    callClickHandle(item) {
        this.currentClient = item;
        this.currentMobileList = item.mobilePhone;
        if(!this.currentMobileList || this.currentMobileList.length < 1)return;
        if(this.currentMobileList.length === 1 && this.currentMobileList[0].mobile){
            this.currentMobile = this.currentMobileList[0].mobile;
            this.nativeCallPhone();
            return;
        }else{
            const phoneArray = [];
            this.currentMobileList.forEach(phoneNumItem => {
                phoneArray.push({
                    text:phoneNumItem.mobile,
                    handler:() => {
                        this.currentMobile = phoneNumItem.mobile;
                        this.nativeCallPhone();
                    }
                });
            });
            this.adpActionSheetController.create({
                title:"选择电话",
                buttons:phoneArray
            }).present();
        }

    }

    /**
     * 后退
     */
    backHandle() {
        this.navCtrl.pop();
    }

    // 到客户详情
    goTOClientDetail(id) {
        this.navCtrl.push('HolderClientDetailPage', {
            clientNum: id
        })
    }

    //进入vip权益
    goToClientVipInterests() {
        this.navCtrl.push('ClientVipInterestsPage');
    }

    /**
     * 下拉刷新
     * @param refresher
     */
    doRefresh(refresher) {
        this.refreshing = true;
        this.pageParams.pageNum = 1;
        if(this.infiniteScroll)this.infiniteScroll.enable(true);
        this.getVipListData(0, () => {
            this.refreshing = false;
            this.filterConditionsShow = true;
            refresher.complete();
        });
    }
    filterConditionsShow = true;
    contentTouchEnd(){
        setTimeout(() => {
            if(!this.refreshing) {
                this.filterConditionsShow = true;
            }
        },500);
    }

    searchedHandle(searchKeyword){
        this.searchKeyword = searchKeyword;
        this.pageParams.pageNum = 1;
        if (this.infiniteScroll) this.infiniteScroll.enable(true);
        if (this.searchKeyword) {
            this.pageParams.condition.keyword = this.searchKeyword.trim();
        } else {
            this.pageParams.condition.keyword = '';
        }
        this.loadingVipListData();
    }

    // 到客户详情
    goToDetail(clientNum) {
        this.navCtrl.push('HolderClientDetailPage', {
            clientNum: clientNum
        })
    }

    selectChangeHandle(e){
        this.pageParams.orderType = e.value;
       // this.loadService.showLoading();
        this.getDataTotal().subscribe((res) => {
            this.getVipListData(0,() => {
                this.loadService.dismissLoading();
            });
        },error2 => {
            this.loadService.dismissLoading()
        });
    }

    ionViewWillLeave(){
        this.clientFilterTool.destroy();
    }
    loadingVipListData(){
        this.loadService.showLoading();
        this.getVipListData(0,() => {
            this.loadService.dismissLoading()
        });
    }
}
